package com.nightpiter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
 * FileLister class
 * 
 * @author Alexander Kim (kim.alexanders@gmail.com)
 * 
 */
public class FileLister extends ListActivity {

	private static final String EMPTYDIR = "<Directory is Empty>";
	private List<String> directoryEntries = new ArrayList<String>();

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		listFiles();
	}

	private void listFiles() {
		File dir = new File(getString(R.string.maps_dir));
		if (!dir.exists()) {
			dir.mkdir();
		}
		for (File file : dir.listFiles()) {
			String fn = file.getName();
			if (fn.endsWith(getString(R.string.maps_extension))) {
				directoryEntries.add(fn);
			}
		}
		if (directoryEntries.size() == 0) {
			directoryEntries.add(EMPTYDIR);
		}

		ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
				R.layout.file_row, this.directoryEntries);

		this.setListAdapter(directoryList);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		Object o = this.getListAdapter().getItem(position);

		setResult(RESULT_OK, o.toString());
		finish();
	}
}